<?php

namespace XWAM\Addon\PXCallSystem\Controller;

/**
 * 管理员页面基类
 *
 * @since 1.0 <2014-6-18> sutroon Added.
 */
class AppbaseController extends \Common\Controller\CommonController {

    /**
     * 是否普通管理员
     * @var boolean
     */
    protected $isAdmin;

    /**
     * 是否普通坐席
     * @var boolean
     */
    protected $isSeat;

    /**
     * 是否超级管理员
     * @var boolean
     */
    protected $isSuperAdmin;

    /**
     * 登录数据
     * @var array
     */
    protected $loginData;

    /**
     * 基类构造方法
     *
     * 检测用户登录状态和加载菜单列表
     */
    public function __construct($check_login = true) {
        sofn_check_website_status();
        parent::__construct();
        // 检查管理员是否登录
        $this->loginData = session(C('USER.SESSION_ID'));
        $loginInfo = $this->loginData;
        if (!$loginInfo) {
            layout(false);
            // 2014-11-4 修正超时错位问题
            die('<script>var url="' . AddonU('Login/index', 'P1') . '";if(window.parent){window.parent.location.href=url}else{location.href=url}</script>');
        }
        if ('SEAT' == $loginInfo['userType'] && 'XCall' == C('USER.USER_KEY')) {
            die('禁止访问');
        }
        $loginInfo['USER_KEY'] = C('USER.USER_KEY');
        if ('TTF' == $loginInfo['USER_KEY'] && 'SEAT' == $loginInfo['userType']) {
            $this->redirect_to_crm();
            exit;
        }

        // 用户权限检查
        if ($check_login) {
            $auth = new \Think\AuthX();
            if (!$auth->check(MODULE_NAME . '/' . ACTION_NAME, $loginInfo['id'])) {
                //$this->error('你没有权限');
            }
        }

        // 设置默认主题
        if (!isset($loginInfo['theme']) || !$loginInfo['theme']) {
            $loginInfo['theme'] = 'start';
        }

        $this->assign('loginData', $loginInfo);

        C('USER.PAGE_SIZE', $loginInfo['pageSize']);

        // 用户类型 (SEAT=座席,ADMIN=普通管理员,SUPERADMIN=超级管理员)
        switch ($loginInfo['userType']) {
            case 'ADMIN':
                $this->isAdmin = TRUE;
                break;
            case 'SUPERADMIN':
                $this->isSuperAdmin = TRUE;
                break;
            case 'SEAT':
                $this->isSeat = TRUE;
                break;
        }
        $this->assign('isSuperAdmin', $this->isSuperAdmin);
    }

    /**
     * 更新登录信息
     * @param $data
     * @since 1.0 2014-9-28 by sutroon
     * @example update_loginData(array('pageSize'=>$pageSize));
     */
    function update_loginData($data) {
        if ($this->loginData) {
            $this->loginData = array_merge($this->loginData, $data);
            session(C('USER.SESSION_ID'), $this->loginData);
        }
    }

    /**
     * 强制提示reload
     * @since 1.0 2014-11-1
     */
    function force_need_reload($action = false) {
        M('asterisk.admin')->where("variable = 'need_reload'")->setField('value', 'true');
        if ($action) {
            $this->jquery_script('window.parent.refresh_page(window.name);');
        }
    }

    public function redirect_to_crm() {
        session(C('USER.SESSION_ID') . '_crm', $this->loginData);
        redirect(AddonU('TTFCrm/Index/index'));
    }

    /**
     * 检测用户权限
     * @param string $key 权限关键词,如 add-user,edit-user,delete-user, 客户管理,新增客户,删除客户等
     * @param bool $end 无权限时是否终止输出,默认true
     * @param array $upr 用户权限数据
     * @return bool
     * @since 1.0 2014-12-29 by sutroon
     * @example 
     *  $this->checkUPR('客户管理');
     *  if (!$this->checkUPR('删除客户', false)) {
     *      $this->act_ajaxReturn(false, '没有权限!');
     *  }
     */
    function checkUPR($key, $end = true, $upr = array()) {
        if (!$upr) {
            $upr = $this->UPR;
        }
        if (!$upr || !isset($upr[$key]) || !$upr[$key]) {
            if ($end) {
                die("没有权限!");
            }
            return false;
        }
        return true;
    }

    /**
     * 添加事件日志
     * @param $action 事件名称，如登录、充值
     * @param $msg 消息内容
     * @param bool $state 状态
     * @param int $userID 用户编号
     * @since 1.0 2014-9-26 by sutroon
     * @example add_user_event_log('登录',"用户登录失败,用户名:$u 密码：$pwd",false);
     */
    public static function add_user_event_log($action, $msg, $state = true, $userID = 0) {
        if (false !== strpos($msg, '{%}')) {
            $msg = str_replace('{%}', false === $state ? '失败' : '成功', $msg);
        }
        $data['userID'] = $userID;
        $data['ip'] = get_client_ip();
        $data['eAction'] = $action;
        $data['eSource'] = $_SERVER['REQUEST_URI'];
        $data['eLevel'] = 'INFO';
        $data['eDesc'] = $msg;
        $data['state'] = $state ? 1 : 0;
        $M = M('db_xcall_log.tuser_event_log');
        $result = $M->add($data);
        if ($result === false) {
            die($M->getDbError());
        }
    }

    /**
     * 显示编辑表单
     * @param string $table 数据表名称
     * @param array $defData 默认数据
     * @since 1.0 2014-7-21 by sutroon; 1.1 2014-12-27 by sutroon 新增 $defData参数
     */
    function itemEdit($table, $defData = array()) {
        $id = I('id');
        $this->assign('data', ($id ? M($table)->find($id) : $defData));
        $this->display();
    }

    /**
     * 保存项目
     * @param string $table 数据表的名称
     * @param array $data 保存的数据
     * @param mixed [string|array] $duplicate 主键重复冲突检测条件, 如array('name' => I('name'), 'barcode' => I('barcode'))或 name like 'abc%'
     * @param string $successUrl 保存成功后跳转的地址
     * @since 1.0 2014-7-31 by sutroon created; 2.0 2014-10-10 by sutroon 重构,支持重复冲突检测.
     * @example itemEditSave('tproduct', $params->getParams(),array('name' => I('name'), 'barcode' => I('barcode')));
     */
    function itemEditSave($table, $data, $duplicate) {
        $id = I('id');
        $M = M($table);
        if ($id && is_numeric($id)) {
            $result = $M->where("id=$id")->save($data);
        } else {
            if ($duplicate) {
                if (is_array($duplicate) && !isset($duplicate['_logic'])) {
                    $duplicate['_logic'] = 'OR';
                }
                if ($M->where($duplicate)->count('id') > 0) {
                    $this->ajaxMsg(false, '记录已存在!');
                }
            }
            $result = $M->add($data);
        }
        if (false === $result) {
            $this->ajaxMsg(false, '保存失败!');
        } else {
            $this->ajaxMsg(true, '保存成功!');
        }
    }

    /**
     * 删除项目
     * @param string $table 数据表名称
     * @since 1.0 2014-7-21 by sutroon
     */
    function itemDelete($table) {
        $id = I('id');
        if (!$id) {
            $this->ajaxMsg(false, '参数无效!');
        }
        $result = M($table)->delete($id);
        $this->ajaxMsg($result, '删除{%}!');
    }

    /**
     * 显示项目列表
     * @param string $table 数据表名称
     * @param string|array $search 查询条件
     * @param array $options 选项
     * @since 1.0 2014-7-18 by sutroon
     */
    function itemList($table, $search, $options = array()) {
        $list = sofunc_get_paging_list($table, $search, $show, $options);
        if (isset($options['siteIDCol']) && false === $options['siteIDCol']) {
            $this->assign('list', $list);
        } else {
            $this->assign('list', sofn_set_site_id_text($list));
        }
        $this->assign('page', $show);
        $this->display2();
    }

    /**
     * 显示树形控件
     * @param string $table 数据表名称
     * @param string $where 查询条件,如: parentID={0},占位符{0}
     * @param int $parentID 父级编号
     * @param array $options 可选参数, 包含: string:FIELDS, string:ORDERBY, bool:CHECKBOX, string:VALUES
     * @since 1.0 2014-10-28 by sutroon
     * @example
     *      $this->assign('uid', $uid);
     *      $rules = M('tuser_member')->where('id=' . $uid)->getField('permissionRule'); // 1,2,3...
     *      $this->itemTreeList('tuser_permission', "parentID={0}", 0, array('ORDERBY' => 'id asc', 'CHECKBOX' => true, 'VALUES' => $rules));
     */
    function itemTreeList($table, $where = 'parentID={0}', $parentID = 0, $options = array()) {
        $options = array_merge(array('FIELDS' => '*', 'ORDERBY' => 'id', 'VALUES' => '', 'CHECKBOX' => false), $options);
        $list = sofunc_get_tree_table($table, $where, $parentID, $options);
        if ($list) {
            $str = $this->itemTreeList_func($list, $options['VALUES'], $options['CHECKBOX']);
            $str = '<ul class="ul-tree">' . substr($str, 4);
        } else {
            $str = '';
        }
        $this->assign('tree', $str);
        $this->display2();
    }

    // itemTreeList内部递归方法 2014-10-28 by sutroon
    private function itemTreeList_func($list, $checked_values, $checkbox = false) {
        $str = '<ul>';
        $id_name = '';
        $value_name = '';
        foreach ($list as $row) {
            if (!$id_name) {
                $keys = array_keys($row);
                $id_name = $keys[0];
                $value_name = $keys[1];
            }
            $str .= '<li>';
            if ($checkbox) {
                $str .= '<input type="checkbox" name="ids[]" value="' . $row[$id_name] . '"' . ($checked_values && false !== strpos(',' . $checked_values . ',', ',' . $row[$id_name] . ',') ? ' checked="checked"' : '') . ' />';
            }
            $str .= '<strong>' . $row[$value_name] . '</strong>';
            if ($row['sub']) {
                $str .= $this->itemTreeList_func($row['sub'], $checked_values, $checkbox);
            }
            $str .= '</li>';
        }
        $str .= '</ul>';
        return $str;
    }

    /**
     * 显示模板内容(区分ajax)
     * @param string $tpl 模版名称
     * @since 1.0 2014-11-18 by sutroon; 1.1 2014-12-25 by sutroon 新增$tpl参数
     */
    function display2($tpl = '') {
        layout(false);
        if (!$tpl) {
            $tpl = ACTION_NAME . '_part';
        }

        if (IS_AJAX) {
            $this->display($tpl);
        } else {
            $this->assign('content', $this->fetch($tpl));
            layout(true);
            $this->display();
        }
    }

}
